#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 crane <crane@crane-pc>
#
# Distributed under terms of the MIT license.

"""

"""

class Solution:
    """
    @param s: a string
    @return: return a integer
    """
    def longestValidParentheses(self, s):
        self.stack = []
        self.count = 0
        self.m = 0
        self.in_match = False

        for idx, c in enumerate(s):
            if c == '(':
                if not self.stack or self.stack[-1] == idx-1:
                    self.stack.append(idx)
                else:
                    # 这里也要做清空
                    # self.m = max(self.m, self.count)
                    self.reset()

            else:
                if self.stack and s[self.stack[-1]] == '(':
                    self.count += 2
                    self.stack.pop()
                else:
                    self.reset()
                    # self.m = max(self.count, self.m)
                    # self.count = 0
                    # self.stack = []

        return max(self.m, self.count)
        # return self.count

    def reset(self):
        self.m = max(self.m, self.count)
        self.count = 0
        self.stack.clear()


def test():
    s = Solution()
    # ret = s.longestValidParentheses('(()')                # 2
    # ret = s.longestValidParentheses(')()())()()()')       # 6
    pars = ")(()(()(((())(((((()()))((((()()(()()())())())()))()()()())(())()()(((()))))()((()))(((())()((()()())((())))(())))())((()())()()((()((())))))((()(((((()((()))(()()(())))((()))()))())"

    ret = s.longestValidParentheses(pars)
    print(ret)


def main():
    print("start main")
    test()

if __name__ == "__main__":
    main()
